package cn.fu.kong;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ReqUtil {
	final static OkHttpClient client = new OkHttpClient
			.Builder()
			.connectTimeout(3, TimeUnit.SECONDS)
			.build();
	
	public static Response postJson(String url, String jsonStr) throws IOException{
		Request req = new Request.Builder()
				.url(url)
				.post(okhttp3.RequestBody
						.create(MediaType.parse("application/json"), jsonStr))
				.build();
		Call call = client.newCall(req);
		
		Response resp = call.execute();
		System.out.println(resp.code());
		return resp;
	}
	
	
	public static Response putJson(String url, String jsonStr) throws IOException{
		Request req = new Request.Builder()
				.url(url)
				.put(okhttp3.RequestBody
						.create(MediaType.parse("application/json"), jsonStr))
				.build();
		Call call = client.newCall(req);
		
		Response resp = call.execute();
		System.out.println(resp.code());
		return resp;
	}
	
	public static Response patchJson(String url, String jsonStr) throws IOException{
		Request req = new Request.Builder()
				.url(url)
				.patch(okhttp3.RequestBody
						.create(MediaType.parse("application/json"), jsonStr))
				.build();
		Call call = client.newCall(req);
		
		Response resp = call.execute();
		System.out.println(resp.code());
		return resp;
	}
	
	public static Response sendDelete(String url) throws IOException{
		Request req = new Request.Builder()
				.url(url)
				.delete()
//				.delete(okhttp3.RequestBody
//						.create(MediaType.parse("application/json"), "{}"))
				.build();
		Call call = client.newCall(req);
		
		Response resp = call.execute();
		System.out.println(resp.code());
		return resp;
	}
	
	public static Response sendGet(String url) throws IOException{
		Request req = new Request.Builder()
				.url(url)
				.get()
				.build();
		Call call = client.newCall(req);
		Response resp = null;
		try {
			resp = call.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resp;
	}
}
